<?php

/**
 * 公共函数库
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/20
 * Time: 17:22
 */


/**
 * 浏览器友好的变量输出
 * @param mixed $var 变量
 * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 * @param string $label 标签 默认为空
 * @param boolean $strict 是否严谨 默认为true
 * @return void|string
 */
function dump($var, $echo = true, $label = null, $strict = true)
{
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    } else
        return $output;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * URL重定向
 * @param string $url 重定向的URL地址
 * @param integer $time 重定向的等待时间（秒）
 * @param string $msg 重定向前的提示信息
 * @return void
 */
function redirect($url, $time = 0, $msg = '')
{
    header("Content-type: text/html; charset=utf-8");
    //多行URL地址支持
    $url = str_replace(array("\n", "\r"), '', $url);
    if (empty($msg))
        $msg = "系统将在{$time}秒之后自动跳转到{$url}！";
    if (!headers_sent()) {
        // redirect
        if (0 === $time) {
            header('Location: ' . $url);
        } else {
            header("refresh:{$time};url={$url}");
            echo($msg);
        }
        exit();
    } else {
        $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
        if ($time != 0)
            $str .= $msg;
        exit($str);
    }
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl()
{
    if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
        return true;
    } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
        return true;
    }
    return false;
}

/**
 * 记录日志
 * @param string $content
 * @param string $log_file
 */
function flog($content = '', $log_file = "sdk.log") {
    if (is_array($content)) {
        $content = urldecode(http_build_query($content));
    }
    if (!$content) {
        $content = "GET: " . urldecode(http_build_query($_GET)) . " POST:" . urldecode(http_build_query($_POST));
    }
    $f = fopen('/data/www/weblogs/' . $log_file, "a");
    if ($f) {
        fputs($f, date("Y-m-d H:i:s") . "\t" . $_SERVER["HTTP_CDN_SRC_IP"] . "\t" . $content . "\r\n");
        fclose($f);
    }
}

/**
 * jsonBack 返回json格式的数据
 * @params data 需要格式化的数据
 * @return json 直接输出json格式的数据,若传callback,则返回jsonp
 */
function jsonBack($data, $log_file = '') {
    if ($log_file) {
        flog($data, $log_file);
    }
    if ($_REQUEST['callback']) {
        echo $_REQUEST['callback'] . "(" . json_encode($data) . ")";
    } else {
        echo json_encode($data);
    }
    exit();
}

//根据第几周获取当周的开始日期与最后日期
function getWeekDate($year,$weeknum){
    $firstdayofyear=mktime(0,0,0,1,1,$year);
    $firstweekday=date('N',$firstdayofyear);
    $firstweenum=date('W',$firstdayofyear);
    if($firstweenum==1){
        $day=(1-($firstweekday-1))+7*($weeknum-1);
        $startdate=date('Y-m-d',mktime(0,0,0,1,$day,$year));
        $enddate=date('Y-m-d',mktime(0,0,0,1,$day+6,$year));
    }else{
        $day=(9-$firstweekday)+7*($weeknum-1);
        $startdate=date('Y-m-d',mktime(0,0,0,1,$day,$year));
        $enddate=date('Y-m-d',mktime(0,0,0,1,$day+6,$year));
    }

    return array($startdate,$enddate);
}








